/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codemobiles.droidslator.activity;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.codemobiles.droidslator.R;
import com.codemobiles.droidslator.manager.LanguageMgr;

/**
 * Demonstrates how to write an efficient list adapter. The adapter used in this
 * example binds to an ImageView and to a TextView for each row in the list.
 * 
 * To work efficiently the adapter implemented here uses two techniques: - It
 * reuses the convertView passed to getView() to avoid inflating View when it is
 * not necessary - It uses the ViewHolder pattern to avoid calling
 * findViewById() when it is not necessary
 * 
 * The ViewHolder pattern consists in storing a data structure in the tag of the
 * view returned by getView(). This data structures contains references to the
 * views we want to bind data to, thus avoiding calls to findViewById() every
 * time getView() is invoked.
 */
public class ListFlagActivity extends ListActivity {
	private static String[] DATA;
	private EfficientAdapter adap;
	private static LanguageMgr langMgr;
	private EditText edtFilter;
	private ImageView imgBack;
	private TextView txvTranslateFromTo;
	private String filterChars = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.pop_list_flag);
		langMgr = new LanguageMgr(this, filterChars);
		DATA = langMgr.getLangList(filterChars);
		adap = new EfficientAdapter(this, langMgr);
		setListAdapter(adap);

		setInitButtonBack();
		setInitEditTextFilter();
		setInitTextViewTranslateFromTo();
	}

	private void setInitTextViewTranslateFromTo() {
		// TODO Auto-generated method stub
		txvTranslateFromTo = (TextView) findViewById(R.id.txvTranslateFromTo);
		txvTranslateFromTo.setText(getIntent().getStringExtra("lastReg").toString());
	}

	private void setInitEditTextFilter() {
		// TODO Auto-generated method stub
		// Set text filter
		edtFilter = (EditText) findViewById(R.id.edtPopup);
		edtFilter.requestFocus();
		edtFilter.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				filterChars = s.toString();
				refresh(filterChars);
			}
		});
	}

	private void refresh(final String filterStr) {
		DATA = langMgr.getLangList(filterStr);
		adap.notifyDataSetChanged();
	}

	private void setInitButtonBack() {
		// TODO Auto-generated method stub
		// Set back button
		imgBack = (ImageView) findViewById(R.id.btnPopupBack);
		imgBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);

		Intent intent = new Intent();
		Bundle b = new Bundle();
		b.putString("FLAG_CODE", adap.getItemCode(position));
		intent.putExtras(b);
		setResult(RESULT_FIRST_USER, intent);
		finish();
	}

	public static class EfficientAdapter extends BaseAdapter implements
			Filterable {
		private LanguageMgr langMgr;
		private LayoutInflater mInflater;
		private Bitmap mIcon1;
		private Context context;

		public EfficientAdapter(Context context, LanguageMgr langMgr) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			this.context = context;
			this.langMgr = langMgr;
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return DATA.length;
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return DATA[position];
		}

		public String getItemCode(int position) {
			return langMgr.getLangCodeByName(DATA[position]);
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_icon_text, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.textFrom = (TextView) convertView
						.findViewById(R.id.textFrom);
				holder.iconFrom = (ImageView) convertView
						.findViewById(R.id.iconFrom);

				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Get flag name and id
			String filename = "flag_"
					+ langMgr.getLangCodeByName(DATA[position]);
			int id = context.getResources().getIdentifier(filename, "drawable",
					context.getString(R.string.root_package));

			// Icons bound to the rows.
			if (id != 0x0) {
				mIcon1 = BitmapFactory.decodeResource(context.getResources(),
						id);
			}

			// Bind the data efficiently with the holder.
			holder.iconFrom.setImageBitmap(mIcon1);
			holder.textFrom.setText(DATA[position]);

			return convertView;
		}

		static class ViewHolder {
			TextView textFrom;
			ImageView iconFrom;
		}

		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

}
